package com.joyd.joydlibexample

import android.app.AlertDialog
import android.content.DialogInterface
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.FrameLayout
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.viewinterop.AndroidView
import com.joyd.joydlib.dev.AccessibilityServiceHelper
import com.joyd.joydlib.dev.ScreenTapHelper
import com.joyd.joydlib.dev.ScreenTapHelper.TapMethod
import android.os.SystemClock
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material3.Button
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlin.concurrent.thread
import androidx.compose.runtime.LaunchedEffect
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class ScreenTapExampleActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MaterialTheme {
                Surface(modifier = Modifier.fillMaxSize()) {
                    ScreenTapExampleScreen()
                }
            }
        }
    }
}

@Composable
fun ScreenTapExampleScreen() {
    val context = LocalContext.current
    var currentMethod by remember {
        mutableStateOf(TapMethod.AUTO)
    }
    var dropdownExpanded by remember {
        mutableStateOf(false)
    }
    
    // 添加一个状态来存储点击测试按钮的引用
    val testButtonRef = remember { mutableStateOf<View?>(null) }
    
    // 获取所有可用的点击方式
    val availableMethods = TapMethod.values()

    Log.e("ScreenTapExample", "检查无障碍服务状态->LaunchedEffect")
    // 启动时自动检查无障碍服务状态
    LaunchedEffect(Unit) {
        // 在后台线程执行检查，避免阻塞UI
        Log.e("ScreenTapExample", "在后台线程执行检查，避免阻塞UI->LaunchedEffect")
        val isAccessibilityEnabled = withContext(Dispatchers.IO) {
            try {
                Log.e("ScreenTapExample", "在后台线程执行检查->AccessibilityServiceHelper")
                AccessibilityServiceHelper.isEnabled(context, JoydLibExampleAccessibilityService::class.java)
            } catch (e: Exception) {
                Log.e("ScreenTapExample", "检查无障碍服务状态失败", e)
                false
            }
        }
        if(!isAccessibilityEnabled) {
            // 跳转到无障碍服务设置页面
            AccessibilityServiceHelper.openAccessibilitySettings(context)
        }
        // 如果当前选择的是无障碍手势方式但服务未启用，提示用户并跳转到设置页面
        if ((currentMethod == TapMethod.ACCESSIBILITY_GESTURE) && !isAccessibilityEnabled) {
            withContext(Dispatchers.Main) {
                Toast.makeText(context, context.getString(R.string.accessibility_service_not_enabled), Toast.LENGTH_SHORT).show()
            }
        }
    }
    
    // 检查是否需要引导用户启用无障碍服务
    fun checkAndRequestAccessibilityService(): Boolean {
        if (currentMethod == TapMethod.ACCESSIBILITY_GESTURE) {
            // 使用实际的服务实现类进行检查
            val isEnabled = AccessibilityServiceHelper.isEnabled(context, JoydLibExampleAccessibilityService::class.java)
            if (!isEnabled) {
                // 在UI线程外获取字符串资源
                val guideTitle = context.getString(R.string.accessibility_service_enable_guide_title)
                val guideMessage = context.getString(R.string.accessibility_service_enable_guide_message)
                val enableButtonText = context.getString(R.string.accessibility_service_enable_button)
                
                // 显示启用引导对话框
                (context as? ComponentActivity)?.runOnUiThread {
                    AlertDialog.Builder(context)
                        .setTitle(guideTitle)
                        .setMessage(guideMessage)
                        .setPositiveButton(enableButtonText) { _, _ ->
                            // 跳转到无障碍设置界面
                            AccessibilityServiceHelper.openAccessibilitySettings(context)
                        }
                        .setNegativeButton(android.R.string.cancel, null)
                        .show()
                }
                return false
            }
        }
        return true
    }

    // 使用无障碍功能模拟点击的方法
    fun simulateClickWithAccessibility(view: View) {
        try {
            // 获取View的位置信息
            val location = IntArray(2)
            view.getLocationOnScreen(location)
            val x = location[0] + view.width / 2
            val y = location[1] + view.height / 2

            // 使用触摸事件模拟点击
            val metaState = 0

            // 创建触摸事件
            val downTime = SystemClock.uptimeMillis()
            val eventTime = SystemClock.uptimeMillis() + 100

            // 发送DOWN事件
            val downEvent = MotionEvent.obtain(
                downTime,
                eventTime,
                MotionEvent.ACTION_DOWN,
                x.toFloat(),
                y.toFloat(),
                metaState
            )
            downEvent.source = android.view.InputDevice.SOURCE_TOUCHSCREEN
            view.dispatchTouchEvent(downEvent)

            // 发送UP事件
            val upEvent = MotionEvent.obtain(
                downTime,
                eventTime + 100,
                MotionEvent.ACTION_UP,
                x.toFloat(),
                y.toFloat(),
                metaState
            )
            upEvent.source = android.view.InputDevice.SOURCE_TOUCHSCREEN
            view.dispatchTouchEvent(upEvent)

            // 回收事件对象
            downEvent.recycle()
            upEvent.recycle()
        } catch (e: Exception) {
            Toast.makeText(context, "模拟点击失败: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }
    // 创建屏幕点击功能函数（发送命令按钮使用）
    fun sendCommand() {
        try {
            // 如果选择了无障碍手势方式，检查服务是否启用
            if (!checkAndRequestAccessibilityService()) {
                return
            }
            
            // 获取点击测试按钮的引用
            val testButton = testButtonRef.value
            if (testButton != null) {
                // 使用无障碍功能模拟点击测试按钮
                simulateClickWithAccessibility(testButton)
                
                // 获取按钮位置信息
                val location = IntArray(2)
                testButton.getLocationOnScreen(location)
                val centerX = location[0] + testButton.width / 2
                val centerY = location[1] + testButton.height / 2
                
                // 显示成功消息
                (context as? ComponentActivity)?.runOnUiThread {
                    Toast.makeText(context, "已点击测试按钮 (${centerX.toInt()}, ${centerY.toInt()}) 使用无障碍功能执行点击", Toast.LENGTH_SHORT).show()
                }
                Log.d("ScreenTapExample", "已点击测试按钮 (${centerX.toInt()}, ${centerY.toInt()}) 使用无障碍功能")
            } else {
                // 如果按钮引用为空，显示错误消息
                (context as? ComponentActivity)?.runOnUiThread {
                    Toast.makeText(context, "无法获取测试按钮引用", Toast.LENGTH_SHORT).show()
                }
                Log.e("ScreenTapExample", "无法获取测试按钮引用")
            }
        } catch (e: Exception) {
            (context as? ComponentActivity)?.runOnUiThread {
                Toast.makeText(context, "点击失败: ${e.message}", Toast.LENGTH_SHORT).show()
            }
            Log.e("ScreenTapExample", "点击失败", e)
        }
    }
    
    // 创建点击测试函数（点击测试按钮使用）
    fun testScreenTap() {
        try {
            // 实现Toast提示点击成功和日志记录
            (context as? ComponentActivity)?.runOnUiThread {
                Toast.makeText(context, "点击测试成功", Toast.LENGTH_SHORT).show()
            }
            Log.d("ScreenTapExample", "点击测试成功")
        } catch (e: Exception) {
            (context as? ComponentActivity)?.runOnUiThread {
                Toast.makeText(context, "点击测试失败: ${e.message}", Toast.LENGTH_SHORT).show()
            }
            Log.e("ScreenTapExample", "点击测试失败", e)
        }
    }
    
    // 创建点击方式变更函数
    fun changeTapMethod(method: TapMethod) {
        currentMethod = method
        dropdownExpanded = false
        
        // 如果选择了无障碍手势方式，检查服务是否启用
        if (method == TapMethod.ACCESSIBILITY_GESTURE) {
            checkAndRequestAccessibilityService()
        }
    }
    
    // 创建确保无障碍服务启用的函数
    fun ensureAccessibilityServiceEnabled() {
        checkAndRequestAccessibilityService()
    }
    
    Column(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = androidx.compose.ui.Alignment.CenterHorizontally
    ) {
        Text(
            text = stringResource(R.string.screen_tap_example_title),
            fontSize = 24.sp,
            modifier = Modifier.padding(bottom = 32.dp)
        )
        
        // 使用AndroidView包装传统Button以获取View引用
        AndroidView(
            modifier = Modifier
                .width(200.dp)
                .padding(bottom = 16.dp),
            factory = {
                Button(it).apply {
                    text = "点击测试"
                    setOnClickListener {
                        testScreenTap()
                    }
                    // 保存对这个按钮的引用
                    testButtonRef.value = this
                }
            }
        )
        
        Button(
            onClick = { sendCommand() },
            modifier = Modifier.width(200.dp)
        ) {
            Text(text = "发送命令")
        }
        
        // 无障碍服务启用按钮
        Button(
            onClick = { ensureAccessibilityServiceEnabled() },
            modifier = Modifier
                .width(200.dp)
                .padding(top = 16.dp)
        ) {
            Text(text = stringResource(R.string.accessibility_service_enable_button))
        }
        
        // 点击方式选择器
        Button(
            onClick = { dropdownExpanded = !dropdownExpanded },
            modifier = Modifier
                .width(200.dp)
                .padding(top = 16.dp)
        ) {
            Text(text = "选择点击方式")
        }
        
        DropdownMenu(
            expanded = dropdownExpanded,
            onDismissRequest = { dropdownExpanded = false },
            modifier = Modifier.width(200.dp)
        ) {
            availableMethods.forEach { method ->
                val enabled = method != TapMethod.ACCESSIBILITY_GESTURE || Build.VERSION.SDK_INT >= Build.VERSION_CODES.N
                DropdownMenuItem(
                    onClick = { changeTapMethod(method) },
                    text = {
                        Text(text = when (method) {
                            TapMethod.AUTO -> stringResource(R.string.screen_tap_method_auto)
                            TapMethod.INPUT_MANAGER -> stringResource(R.string.screen_tap_method_input_manager)
                            TapMethod.INSTRUMENTATION -> stringResource(R.string.screen_tap_method_instrumentation)
                            TapMethod.REFLECTION -> stringResource(R.string.screen_tap_method_reflection)
                            TapMethod.ROOT -> stringResource(R.string.screen_tap_method_root)
                            TapMethod.INPUT_COMMAND -> stringResource(R.string.screen_tap_method_input_command)
                            TapMethod.ACCESSIBILITY_GESTURE -> stringResource(R.string.screen_tap_method_accessibility_gesture)
                        })
                    },
                    enabled = enabled
                )
            }
        }
        
        // 当前点击方式显示
        Text(
            text = "当前点击方式: " + when (currentMethod) {
                TapMethod.AUTO -> stringResource(R.string.screen_tap_method_auto)
                TapMethod.INPUT_MANAGER -> stringResource(R.string.screen_tap_method_input_manager)
                TapMethod.INSTRUMENTATION -> stringResource(R.string.screen_tap_method_instrumentation)
                TapMethod.REFLECTION -> stringResource(R.string.screen_tap_method_reflection)
                TapMethod.ROOT -> stringResource(R.string.screen_tap_method_root)
                TapMethod.INPUT_COMMAND -> stringResource(R.string.screen_tap_method_input_command)
                TapMethod.ACCESSIBILITY_GESTURE -> stringResource(R.string.screen_tap_method_accessibility_gesture)
            },
            modifier = Modifier.padding(top = 16.dp)
        )
    }
}

@Preview(showBackground = true)
@Composable
fun ScreenTapExamplePreview() {
    MaterialTheme {
        Surface(modifier = Modifier.fillMaxSize()) {
            ScreenTapExampleScreen()
        }
    }
}